﻿using LPP.Entity;
using LPP.Repository;
using System.Threading.Tasks;
using System.Collections.Generic;
using LPP.Entity.Orders;
using LPP.Service.OrderServices;
using System;
using LPP.Core.Dtos;

namespace LPP.Services
{
    public class OrderService : IOrderService
    {
        private readonly IOrderRepository _orderRepository;
        private readonly decimal PLATFORM_COMMISSION_RATE = 0.5m; // 平台抽成比例50%

        public OrderService(IOrderRepository orderRepository)
        {
            _orderRepository = orderRepository;
        }

        // 创建订单方法，保证事务性
        public async Task<bool> CreateOrderAsync(Order order, List<OrderDetail> orderDetails)
        {
            using (var transaction = await _orderRepository.BeginTransactionAsync())
            {
                try
                {
                    // 保存订单
                    await _orderRepository.AddOrderAsync(order);

                    // 为每个订单明细设置OrderID并保存
                    foreach (var detail in orderDetails)
                    {
                        detail.OrderID = order.OrderID; // 关联订单
                        detail.AssignedAt = DateTime.Now;
                        CalculateIncome(detail);
                        await _orderRepository.InsertOrderDetailAsync(detail);
                        // 计算收入分成
                       
                    }

                    // 提交事务
                    await transaction.CommitAsync();
                    return true;
                }
                catch
                {
                    await transaction.RollbackAsync();
                    return false;
                }
            }
        }
        // 计算收入分成
        private void CalculateIncome(OrderDetail detail)
        {
            detail.PlatformIncome = detail.TotalPrice * PLATFORM_COMMISSION_RATE;
            detail.WorkerIncome = detail.TotalPrice - detail.PlatformIncome;
            detail.CommissionRate = PLATFORM_COMMISSION_RATE;
        }
        // 获取工人收入统计
        public async Task<WorkerIncomeStatisticsDto> GetWorkerIncomeStatisticsAsync(int workerId, DateTime? startDate = null, DateTime? endDate = null)
        {
            var completedOrders = await _orderRepository.GetWorkerCompletedOrdersAsync(workerId, startDate, endDate);

            return new WorkerIncomeStatisticsDto
            {
                TotalIncome = completedOrders.Sum(od => od.WorkerIncome),
                CompletedOrders = completedOrders.Count(),
                MonthlyIncome = completedOrders
                    .Where(od => od.CompletedTime?.Month == DateTime.Now.Month)
                    .Sum(od => od.WorkerIncome),
                PendingOrders = await _orderRepository.GetWorkerPendingOrdersCountAsync(workerId)
            };
        }
        // 完成订单
        public async Task CompleteOrderAsync(string orderId)
        {
            using (var transaction = await _orderRepository.BeginTransactionAsync())
            {
                try
                {
                    var order = await _orderRepository.GetOrderByIdAsync(orderId);
                    if (order == null)
                        throw new KeyNotFoundException($"Order {orderId} not found");

                    order.Status = OrderStatus.Completed;
                    order.CompletedTime = DateTime.Now;

                    foreach (var detail in order.OrderDetails)
                    {
                        detail.CompletedAt = DateTime.Now;
                    }

                    await _orderRepository.UpdateOrderAsync(order);
                    await transaction.CommitAsync();
                }
                catch
                {
                    await transaction.RollbackAsync();
                    throw;
                }
            }
        }
        public async Task<PlatformIncomeStatisticsDto> GetPlatformIncomeStatisticsAsync(DateTime? startDate = null, DateTime? endDate = null)
        {
            var completedOrders = await _orderRepository.GetCompletedOrdersAsync(startDate, endDate);

            return new PlatformIncomeStatisticsDto
            {
                TotalIncome = completedOrders.Sum(od => od.PlatformIncome),
                OrderCount = completedOrders.Count(),
                WorkerCount = completedOrders.Select(od => od.WorkerID).Distinct().Count(),
                AverageOrderAmount = completedOrders.Any() ?
                    completedOrders.Average(od => od.Amount) : 0
            };
        }
        public async Task<Order> CreateOrderAsync(Order order)
        {

            // 调用仓储层保存订单
            await _orderRepository.AddOrderAsync(order);
            return order;
        }


        public async Task<Order> GetOrderByIdAsync(string orderId)
        {
            var order = await _orderRepository.GetOrderByIdAsync(orderId);

            if (order == null)
            {
                throw new KeyNotFoundException($"Order with ID {orderId} was not found.");
            }

            return order;
        }
        public async Task<List<Order>> GetUserOrdersAsync(int userId)
        {
            return await _orderRepository.GetUserOrdersAsync(userId);
        }


        public async Task UpdateOrderAsync(Order order)
        {
            var existingOrder = await _orderRepository.GetOrderByIdAsync(order.OrderID);

            if (existingOrder == null)
            {
                throw new Exception("订单不存在");
            }

            // 更新订单属性
            existingOrder.Status = order.Status;
            existingOrder.Amount = order.Amount;
            existingOrder.OrderDetails = order.OrderDetails; // 更新订单明细

            // 保存更新
            await _orderRepository.UpdateOrderAsync(existingOrder);
        }
        public async Task<List<OrderDetail>> GetUnfinishedOrderDetailsAsync()
        {
            return await _orderRepository.GetUnfinishedOrderDetailsAsync();
        }

    }
    // 添加相关 DTO
    public class WorkerIncomeStatisticsDto
    {
        public decimal TotalIncome { get; set; }
        public decimal MonthlyIncome { get; set; }
        public int CompletedOrders { get; set; }
        public int PendingOrders { get; set; }
    }

    public class PlatformIncomeStatisticsDto
    {
        public decimal TotalIncome { get; set; }
        public int OrderCount { get; set; }
        public int WorkerCount { get; set; }
        public decimal AverageOrderAmount { get; set; }
    }
}

